@{
    var type = (string)Model.ChartType?.ToString() ?? "bar";
    var labels = (IEnumerable<string>)Model.Labels;
    var datasets = (IEnumerable<ChartJsDataSet>)Model.DataSets;
    var options = Model.Options as object ?? new { };
    var backgroundColor = Model.BackgroundColor as string ?? "white";
    var dataLabelConfiguration = Model.DataLabelConfiguration as DataLabelConfiguration;
    var withDataLabels = dataLabelConfiguration?.Enabled == true;

    const string blockName = "chart";
    const string containerName = blockName + "__container";
    const string canvasName = blockName + "__canvas";

    var canvasId = $"{canvasName}_{Guid.NewGuid():N}";
}
<div class="@containerName">
    <canvas id="@canvasId" class="@canvasName"></canvas>
</div>

<script asp-name="@ResourceNames.Library" at="Foot"></script>
<script asp-name="@ResourceNames.Annotation" at="Foot"></script>

@if (withDataLabels)
{
    <script asp-name="@ResourceNames.DataLabels" at="Foot"></script>
}

<script at="Foot">
    // No jQuery because it's not required and this is the only custom event handler in the whole module.
    function ready(callback) { return document.readyState !== 'loading' ? callback() : document.addEventListener('DOMContentLoaded', callback); }

    ready(function () {
        @if (withDataLabels)
        {
            <text>
                Chart.plugins.register(ChartDataLabels);
            </text>
        }

        const configuration =
        {
            type: @Json.Serialize(type),
            data: {
                labels: @Json.Serialize(labels),
                datasets: @Json.Serialize(datasets),
            },
            options: @Json.Serialize(options),
            plugins: [{
                beforeDraw: function(chart) {
                    const canvasContext = chart.ctx;
                    canvasContext.fillStyle = @Json.Serialize(backgroundColor);
                    canvasContext.fillRect(0, 0, canvasContext.canvas.clientWidth, canvasContext.canvas.clientHeight);
                }
            }]
        };

        if (configuration.options) {
            if (!configuration.options.plugins) configuration.options.plugins = {};
            if (!configuration.options.plugins.datalabels) configuration.options.plugins.datalabels = {};

            const dataLabelConfiguration = @Json.Serialize(dataLabelConfiguration) ;
            configuration.options.plugins.datalabels.formatter = function(value) {
                if (typeof value !== 'number') return value;

                if (dataLabelConfiguration.roundNumbers) value = Math.round(value);
                return value.toString() + dataLabelConfiguration.suffix;
            };
        }

        new Chart(document.getElementById('@canvasId'), configuration);
    });
</script>
